package com.quanxiaoha.weblog.common.utils;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

public class LuckyDraw {
    // 奖品类型
    public static final Integer THANK_YOU = 0;
    public static final Integer POINTS_1 = 1;
    public static final Integer POINTS_2 = 2;
    public static final Integer POINTS_7 = 7;
    public static final Integer POINTS_9 = 9;
    public static final Integer POINTS_10 = 10;

    // 奖品概率分布
    private static final Map<Integer, Double> PRIZE_PROBABILITIES = new HashMap<>();
    static {
        // 基础奖品概率
        PRIZE_PROBABILITIES.put(THANK_YOU, 0.45);  // 谢谢参与 45%
        PRIZE_PROBABILITIES.put(POINTS_1, 0.225);  // 1积分 22.5%
        PRIZE_PROBABILITIES.put(POINTS_2, 0.225);  // 2积分 22.5%
        
        // 稀有奖品概率
        PRIZE_PROBABILITIES.put(POINTS_7, 0.02);   // 7积分 2%
        PRIZE_PROBABILITIES.put(POINTS_9, 0.01);   // 9积分 1%
        PRIZE_PROBABILITIES.put(POINTS_10, 0.01);  // 10积分 1%
    }

    /**
     * 进行抽奖
     * @return 抽中的奖品
     */
    public static Integer draw() {
        double random = new SecureRandom().nextDouble();
        double cumulativeProbability = 0.0;

        for (Map.Entry<Integer, Double> entry : PRIZE_PROBABILITIES.entrySet()) {
            cumulativeProbability += entry.getValue();
            if (random <= cumulativeProbability) {
                return entry.getKey();
            }
        }

        return 0; // 默认返回谢谢参与
    }


    /**
     * 模拟多次抽奖并统计结果
     * @param times 抽奖次数
     */
    public static void simulateDraws(int times) {
        Map<Integer, Integer> results = new HashMap<>();
        int totalPoints = 0;

        // 初始化统计
        for (Integer prize : PRIZE_PROBABILITIES.keySet()) {
            results.put(prize, 0);
        }

        // 进行抽奖
        for (int i = 0; i < times; i++) {
            Integer prize = draw();
            results.put(prize, results.get(prize) + 1);
            totalPoints += prize;
        }

        // 输出统计结果
        System.out.printf("\n模拟%d次抽奖结果：\n", times);
        System.out.println("----------------------------------------");
        for (Map.Entry<Integer, Integer> entry : results.entrySet()) {
            double percentage = (double) entry.getValue() / times * 100;
            System.out.printf("%s: %d次 (%.2f%%)\n", 
                entry.getKey(), entry.getValue(), percentage);
        }
        System.out.println("----------------------------------------");
        System.out.printf("总获得积分：%d\n", totalPoints);
        System.out.printf("平均每次获得积分：%.2f\n", (double) totalPoints / times);
    }

    public static void main(String[] args) {
        // 模拟10000次抽奖
        simulateDraws(10000);
    }
} 